package com.chenfan.magic.config;

import com.chenfan.magic.constant.ParamConstants;
import com.chenfan.magic.service.IParamServiceProvider;
import lombok.AllArgsConstructor;
import org.python.util.PythonInterpreter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

/**
 * 解释器配置
 *
 * @author 周夕
 * @date 2020-02-26 15:03
 */
@Configuration
@AllArgsConstructor
public class InterpreterConfiguration {

    private IParamServiceProvider paramServiceProvider;

    @Bean(name = "pythonInterpreterEngine")
    public PythonInterpreter pythonInterpreterEngine() {
        Properties props = new Properties();
        props.put("python.import.site", "false");
        props.put("python.console.encoding", "UTF-8");
        props.put("python.security.respectJavaAccessibility", "false");
        Properties preprops = System.getProperties();
        PythonInterpreter.initialize(preprops, props, new String[0]);
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.exec("import sys");
        //jython自己的库
        interpreter.exec("sys.path.append('" + paramServiceProvider.get(ParamConstants.magic_interpreter_python_jythonlibpath) + "')");
        //jython自己的库
        interpreter.exec("sys.path.append('" + paramServiceProvider.get(ParamConstants.magic_interpreter_python_jythonlibsitepathpath) + "')");
        //自己写的库
        interpreter.exec("sys.path.append('" + paramServiceProvider.get(ParamConstants.magic_interpreter_python_jythoncustomlibpath) + "')");
        return interpreter;
    }

    @Bean(name = "javaClassLoaderPath")
    public String javaClassLoaderPath() {
        String path = paramServiceProvider.get(ParamConstants.magic_interpreter_java_classpath);
        return path == null ? "" : path;
    }
}
